package com.fakesmoker.aidawnda.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fakesmoker.aidawnda.annotation.AuthCheck;
import com.fakesmoker.aidawnda.common.BaseResponse;
import com.fakesmoker.aidawnda.common.DeleteRequest;
import com.fakesmoker.aidawnda.common.ErrorCode;
import com.fakesmoker.aidawnda.common.ResultUtils;
import com.fakesmoker.aidawnda.constant.UserConstant;
import com.fakesmoker.aidawnda.exception.BusinessException;
import com.fakesmoker.aidawnda.exception.ThrowUtils;
import com.fakesmoker.aidawnda.model.dto.team.*;
import com.fakesmoker.aidawnda.model.entity.Team;
import com.fakesmoker.aidawnda.model.entity.User;
import com.fakesmoker.aidawnda.model.vo.TeamVO;
import com.fakesmoker.aidawnda.service.TeamService;
import com.fakesmoker.aidawnda.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户回用户标签表接口
 *
 * @author lcy
 */
@RestController
@RequestMapping("/team")
@Slf4j
public class TeamController {

    @Resource
    private TeamService teamService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建用户回用户标签表
     *
     * @param teamAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(teamAddRequest == null, ErrorCode.PARAMS_ERROR);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        // 数据校验
        teamService.validTeam(team, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        team.setUserId(loginUser.getId());
        // 写入数据库
        Long teamId = teamService.addTeam(team, loginUser);
        return ResultUtils.success(teamId);
    }

    /**
     * 删除用户回用户标签表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Team oldTeam = teamService.getById(id);
        ThrowUtils.throwIf(oldTeam == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅校验你是不是队伍的队长或者管理员
        if (!oldTeam.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = teamService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新用户回用户标签表（仅管理员可用）
     *
     * @param teamUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest) {
        if (teamUpdateRequest == null || teamUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Team team = new Team();
        BeanUtils.copyProperties(teamUpdateRequest, team);
        // 数据校验
        teamService.validTeam(team, false);
        // 判断是否存在
        long id = teamUpdateRequest.getId();
        Team oldTeam = teamService.getById(id);
        ThrowUtils.throwIf(oldTeam == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = teamService.updateById(team);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户回用户标签表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<TeamVO> getTeamVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Team team = teamService.getById(id);
        ThrowUtils.throwIf(team == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(teamService.getTeamVO(team, request));
    }

    /**
     * 分页获取用户回用户标签表列表（仅管理员可用）
     *
     * @param teamQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Team>> listTeamByPage(@RequestBody TeamQueryRequest teamQueryRequest) {
        long current = teamQueryRequest.getCurrent();
        long size = teamQueryRequest.getPageSize();
        // 查询数据库
        Page<Team> teamPage = teamService.page(new Page<>(current, size),
                teamService.getQueryWrapper(teamQueryRequest));
        return ResultUtils.success(teamPage);
    }


    /**
     * 分页获取当前登录用户创建的用户回用户标签表列表
     *
     * @param teamQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<TeamVO>> listMyTeamVOByPage(@RequestBody TeamQueryRequest teamQueryRequest,
                                                         HttpServletRequest request) {
        ThrowUtils.throwIf(teamQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        teamQueryRequest.setUserId(loginUser.getId());
        long current = teamQueryRequest.getCurrent();
        long size = teamQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Team> teamPage = teamService.page(new Page<>(current, size),
                teamService.getQueryWrapper(teamQueryRequest));
        // 获取封装类
        return ResultUtils.success(teamService.getTeamVOPage(teamPage, request));
    }

    /**
     * 编辑用户回用户标签表（给用户使用）
     *
     * @param teamEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editTeam(@RequestBody TeamEditRequest teamEditRequest, HttpServletRequest request) {
        if (teamEditRequest == null || teamEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Team team = new Team();
        BeanUtils.copyProperties(teamEditRequest, team);
        // 数据校验
        teamService.validTeam(team, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = teamEditRequest.getId();
        Team oldTeam = teamService.getById(id);
        ThrowUtils.throwIf(oldTeam == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldTeam.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = teamService.updateById(team);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion

    /**
     * 分页获取用户回用户标签表列表（封装类）
     *
     * @param teamQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<TeamVO>> listTeamVOByPage(@RequestBody TeamQueryRequest teamQueryRequest,
                                                       HttpServletRequest request) {
        long current = teamQueryRequest.getCurrent();
        long size = teamQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        Page<Team> teamPage = teamService.page(new Page<>(current, size),
                teamService.getPageQueryWrapper(teamQueryRequest, request));
        // 获取封装类
        return ResultUtils.success(teamService.getTeamVOPage(teamPage, request));
    }

    /**
     * 用户可以加入队伍
     *
     * @param userJoinTeamRequest
     * @param request
     * @return
     */
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody UserJoinTeamRequest userJoinTeamRequest,
                                          HttpServletRequest request) {
        ThrowUtils.throwIf(userJoinTeamRequest == null, ErrorCode.PARAMS_ERROR);

        Boolean result = teamService.joinTeam(userJoinTeamRequest, request);
        return  ResultUtils.success(result);
    }
/**
     * 用户可以退出队伍
     *
     * @param userQuitTeamRequest
     * @param request
     * @return
     */
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody UserQuitTeamRequest userQuitTeamRequest,
                                          HttpServletRequest request) {
        ThrowUtils.throwIf(userQuitTeamRequest == null, ErrorCode.PARAMS_ERROR);

        Boolean result = teamService.quitTeam(userQuitTeamRequest, request);

        return ResultUtils.success(result);
    }


    /**
     * 幂等性优化 退出队伍幂等
     * @return
     */
    @GetMapping("/generate/id")
    public BaseResponse<Long> generateUserTeamQuitId() {
        return ResultUtils.success(IdUtil.getSnowflakeNextId());
    }


}
